﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using LRSTaxServices.DAL;
using LRSTaxServices.DAL.dsRolesTableAdapters;
using LRSTaxServices.Common;

namespace LRSTaxServices.Biz
{
    /// <summary>
    /// Roles Business Object
    /// </summary>

    public class Role : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected Role() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the Roles.
        /// </summary>
        public int LU_RoleID
        {
            get { return _roleID; }
            set
            {
                if (_roleID != value)
                {
                    if (OnPropertyChanging("LU_RoleID", _roleID, value))
                    {
                        int oldValue = _roleID;
                        _roleID = value;

                        OnPropertyChanged("LU_RoleID", oldValue, value);
                    }
                }
            }
        }  private int _roleID = -1;

        /// <summary>
        /// Role Name.
        /// </summary>
        public string RoleName
        {
            get { return _rolename; }
            set
            {
                if (_rolename != value)
                {
                    if (OnPropertyChanging("RoleName", _rolename, value))
                    {
                        string oldValue = _rolename;
                        _rolename = value;
                        OnPropertyChanged("RoleName", oldValue, value);
                    }
                }
            }
        }  private string _rolename = null;


        /// <summary>
        /// Description.
        /// </summary>
        public string Description
        {
            get { return _description; }
            set
            {
                if (_description != value)
                {
                    if (OnPropertyChanging("Description", _description, value))
                    {
                        string oldValue = _description;
                        _description = value;
                        OnPropertyChanged("Description", oldValue, value);
                    }
                }
            }
        }  private string _description = null;


        /// <summary>
        /// Display Order.
        /// </summary>
        public int DisplayOrder
        {
            get { return _displayorder; }
            set
            {
                if (_displayorder != value)
                {
                    if (OnPropertyChanging("DisplayOrder", _displayorder, value))
                    {
                        int oldValue = _displayorder;
                        _displayorder = value;
                        OnPropertyChanged("DisplayOrder", oldValue, value);
                    }
                }
            }
        }  private int _displayorder = -1;

        /// <summary>
        /// True iff the Admin has made this JobCategory Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty JobCategory object.
        /// </summary>
        public static Role CreateNew()
        {
            Role obj = new Role();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;
            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static Role CreateNew(RolesCollection collection)
        {
            Role obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (Role role in collection)
            {
                if (role.LU_RoleID < minVal)
                    minVal = role.LU_RoleID;
            }
            obj.LU_RoleID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllRoles

        /// <summary>
        /// Returns a collection of all Roles.
        /// </summary>
        public static RolesCollection GetAllRoles()
        {
            RolesTableAdapter adapter = new RolesTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsRoles.RolesDataTable tbl = adapter.GetData(null);

            RolesCollection list = new RolesCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsRoles.RolesRow row in tbl.Rows)
                {
                    Role role = new Role();
                    RelationalToObject(role, row);
                    list.Add(role);
                }
            }

            return (list);
        }

        #endregion

        #region GetRoleByID

        /// <summary>
        /// Returns a Role object for the specified 'RolesID' or null if no Roles with the specified parameter(s) exists.
        /// </summary>
        public static Role GetRoleByID(int roleid)
        {
            RolesTableAdapter adapter = new RolesTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsRoles.RolesDataTable tbl = adapter.GetData(roleid);

            if (tbl.Rows.Count == 1)
            {
                Role role = new Role();
                RelationalToObject(role, tbl.Rows[0]);
                return (role);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'Role' returned more than one Role record.");

            return (null);
        }

        #endregion

        #region GetRoleByRoleName

        /// <summary>
        /// Returns an Role object for the specified 'RoleName' or null if no Role with the specified parameter(s) exists.
        /// </summary>
        public static Role GetRoleByRoleName(string rolename)
        {
            RolesTableAdapter adapter = new RolesTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsRoles.RolesDataTable tbl = adapter.GetDataByRoleName(rolename);

            if (tbl.Rows.Count == 1)
            {
                Role role = new Role();
                RelationalToObject(role, tbl.Rows[0]);
                return (role);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'RoleName' returned more than one Role.");

            return (null);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified Role.
        /// </summary>
        public static void Update(Role obj)
        {
            bool updateRole = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateRole = (obj.ObjState != ObjectState.Unchanged);

                if (!updateRole)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsRoles.RolesDataTable tbl = null;
            if (updateRole)
            {
                RolesTableAdapter adapter = new RolesTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();

                tbl = new dsRoles.RolesDataTable();
                dsRoles.RolesRow row = tbl.NewRolesRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (LU_RoleID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("RoleID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                if ((RoleName == null) || (RoleName.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("RoleNmae", "Role Name is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {

                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("Role: LU_RoleID={0}, RoleName={1}, {2}", LU_RoleID, RoleName, DisplayOrder));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more Roles objects.
    /// </summary>

    public class RolesCollection : List<Role>
    {
        #region Types

        public class UserComparer : IComparer<Role>
        {
            public int Compare(Role r1, Role r2)
            {
                return (String.Compare(r1.RoleName, r2.RoleName));
            }
        }

        #endregion

        #region Public Methods

        #region FindByRoleID

        public Role FindByRoleID(int roleID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].LU_RoleID == roleID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindRoleByRoleName

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public Role FindRoleByRoleName(string RoleName)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].RoleName == RoleName)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion
    }
}
